package com.fbt.transfer.app.driver.ui.grab;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.hutool.core.date.DateUtil;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.fbt.transfer.app.driver.activity.OrderDetailActivity;
import com.fbt.transfer.app.driver.databinding.FragmentGrabBinding;
import com.fbt.transfer.app.driver.model.OrderStatusEnum;
import com.fbt.transfer.app.driver.model.OrderTypeEnum;
import com.fbt.transfer.app.driver.model.ServiceType;
import com.fbt.transfer.app.driver.model.grab.WaitOrderUnit;
import com.fbt.transfer.app.driver.model.index.OrderUnitVo;
import com.fbt.transfer.app.driver.util.ZMToast;
import java.text.SimpleDateFormat;
import java.util.*;

public class GrabFragment extends Fragment {

  private FragmentGrabBinding fragmentGrabBinding;
  private GrabViewModel grabViewModel = null;
  private GrabOrderAdapter adapter = null;
  private boolean isLoading = false;
  static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.SIMPLIFIED_CHINESE);
  private String selectedAppointmentTime = null;
  private RadioGroup rgServiceType = null;
  private OptionsPickerView pvTime = null;

  public GrabFragment() {
    fragmentGrabBinding = null;
  }

  private void initView() {
    // 初始化RecyclerView
    RecyclerView recyclerView = fragmentGrabBinding.recyclerView;
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    adapter = new GrabOrderAdapter(getContext());
    // Apply card beautification in adapter
    adapter.setBeautifyCard(true);
    recyclerView.setAdapter(adapter);

    // 设置空视图文本
    TextView emptyText = fragmentGrabBinding.emptyView.tvEmptyText;
    emptyText.setText("休息一会，暂无更多数据");

    // 初始化车型选择
    rgServiceType = fragmentGrabBinding.rgServiceType;
  }

  public View onCreateView(
      @NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    grabViewModel = new ViewModelProvider(this).get(GrabViewModel.class);

    fragmentGrabBinding = FragmentGrabBinding.inflate(inflater, container, false);
    View root = fragmentGrabBinding.getRoot();

    initView();
    initTimePicker();
    initListener();
    observeViewModel();

    // 加载第一页数据
    grabViewModel.loadFirstPage(null, null, null);

    return root;
  }

  private void initTimePicker() {
    Calendar now = Calendar.getInstance();
    List<String> dates = new ArrayList<>();
    List<List<String>> hours = new ArrayList<>();
    List<List<List<String>>> minutes = new ArrayList<>();

    // 构建第一列数据（未来15天）
    for (int i = 0; i <= 15; i++) {
      Calendar calendar = (Calendar) now.clone();
      calendar.add(Calendar.DAY_OF_MONTH, i);
      if (i == 0) {
        dates.add("今天");

        // 如果是今天，小时列表只能从当前小时开始
        int currentHour = now.get(Calendar.HOUR_OF_DAY);
        int currentMinute = now.get(Calendar.MINUTE);

        // 第二列：小时（从当前小时到23）
        List<String> todayHourList = new ArrayList<>();
        for (int h = currentHour; h <= 23; h++) {
          todayHourList.add(String.format("%02d", h));
        }
        hours.add(todayHourList);

        // 第三列：分钟（对于当前小时，只能从当前分钟之后的10分钟间隔开始）
        List<List<String>> todayMinutesList = new ArrayList<>();
        for (int h = currentHour; h <= 23; h++) {
          List<String> minuteList = new ArrayList<>();
          if (h == currentHour) {
            // 对于当前小时，只显示大于当前分钟的10分钟间隔
            int startMinute = ((currentMinute / 10) * 10) + 10; // 向上取整到下一个10分钟
            for (int m = startMinute; m <= 50; m += 10) {
              minuteList.add(String.format("%02d", m));
            }
            // 如果没有可选的分钟（当前时间接近小时末尾），添加下一个小时的00分
            if (minuteList.isEmpty() && h < 23) {
              minuteList.add("00");
            }
          } else {
            // 对于未来的小时，显示所有10分钟间隔
            for (int m = 0; m <= 50; m += 10) {
              minuteList.add(String.format("%02d", m));
            }
          }
          todayMinutesList.add(minuteList);
        }
        minutes.add(todayMinutesList);
      } else {
        // 对于未来的日期
        if (i == 1) {
          dates.add("明天");
        } else {
          SimpleDateFormat sdf = new SimpleDateFormat("M月d日 E", Locale.SIMPLIFIED_CHINESE);
          dates.add(sdf.format(calendar.getTime()));
        }

        // 第二列：小时（0-23）
        List<String> hourList = new ArrayList<>();
        for (int h = 0; h <= 23; h++) {
          hourList.add(String.format("%02d", h));
        }
        hours.add(hourList);

        // 第三列：分钟（0, 10, 20, 30, 40, 50）
        List<List<String>> dayMinutesList = new ArrayList<>();
        for (int h = 0; h <= 23; h++) {
          List<String> minuteList = new ArrayList<>();
          for (int m = 0; m <= 50; m += 10) {
            minuteList.add(String.format("%02d", m));
          }
          dayMinutesList.add(minuteList);
        }
        minutes.add(dayMinutesList);
      }
    }
    pvTime =
        new OptionsPickerBuilder(
                getContext(),
                (options1, options2, options3, v) -> {
                  // 根据选择的日期获取对应的小时列表
                  List<String> hourList = hours.get(options1);
                  String selectedHour = hourList.get(options2);

                  // 根据选择的日期和小时获取对应的分钟列表
                  List<String> minuteList = new ArrayList<>();
                  // 安全地获取分钟列表
                  if (options1 < minutes.size() && options2 < minutes.get(options1).size()) {
                    minuteList = minutes.get(options1).get(options2);
                  } else {
                    // 如果无法获取到分钟列表，创建一个默认的
                    for (int m = 0; m <= 50; m += 10) {
                      minuteList.add(String.format("%02d", m));
                    }
                  }

                  // 确保options3不会越界
                  if (options3 >= minuteList.size()) {
                    options3 = 0;
                  }
                  String selectedMinute = minuteList.get(options3);

                  Calendar selectedCalendar = (Calendar) now.clone();
                  selectedCalendar.add(Calendar.DAY_OF_MONTH, options1);
                  selectedCalendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(selectedHour));
                  selectedCalendar.set(Calendar.MINUTE, Integer.parseInt(selectedMinute));

                  // 如果是"今天"，确保选中的时间大于当前时间
                  if (options1 == 0 && selectedCalendar.before(now)) {
                    ZMToast.err(getContext(), "请选择大于当前时间的预约时间");
                    return;
                  }
                  selectedAppointmentTime = sdf.format(selectedCalendar.getTime());
                  fragmentGrabBinding.tvAppointmentTime.setText(
                      DateUtil.format(selectedCalendar.getTime(), "yyyy-MM-dd HH:mm"));
                  applyFilters();
                })
            .setTitleText("选择预约时间")
            .setOutSideCancelable(true)
            .setOptionsSelectChangeListener(
                (options1, options2, options3) -> {
                  // 更新小时列表
                  List<String> hourList = hours.get(options1);
                  // 获取对应的分钟列表
                  List<String> minuteList;
                  if (options1 == 0) { // 今天
                    // 今天的分钟列表是二维数组
                    if (options2 < minutes.get(options1).size()) {
                      minuteList = minutes.get(options1).get(options2);
                    } else {
                      minuteList = new ArrayList<>();
                    }
                  } else { // 其他日期
                    // 其他日期的分钟列表也是二维数组
                    if (options2 < minutes.get(options1).size()) {
                      minuteList = minutes.get(options1).get(options2);
                    } else {
                      minuteList = new ArrayList<>();
                    }
                  }
                  // 更新数据源
                  pvTime.setNPicker(dates, hourList, minuteList);
                  // 恢复选中状态，但保持第一列的新选择
                  pvTime.setSelectOptions(options1, options2, options3);
                })
            .build();
    // 默认加载第一组数据（今天）
    Calendar currentTime = Calendar.getInstance();
    int currentHour = currentTime.get(Calendar.HOUR_OF_DAY);
    int currentMinute = currentTime.get(Calendar.MINUTE);

    // 计算默认选中的小时和分钟索引
    int defaultHourIndex = 0; // 默认选中当前小时
    int defaultMinuteIndex = 0; // 默认选中当前分钟之后的第一个可选分钟

    // 如果是今天，计算分钟的默认索引
    List<String> defaultMinuteList = new ArrayList<>();

    // 安全地获取分钟列表
    if (minutes.size() > 0 && minutes.get(0).size() > 0) {
      defaultMinuteList = minutes.get(0).get(0);

      if (!defaultMinuteList.isEmpty()) {
        int nextMinute = ((currentMinute / 10) * 10) + 10; // 向上取整到下一个10分钟
        for (int i = 0; i < defaultMinuteList.size(); i++) {
          if (Integer.parseInt(defaultMinuteList.get(i)) >= nextMinute) {
            defaultMinuteIndex = i;
            break;
          }
        }

        // 如果当前小时没有可选的分钟（当前时间接近小时末尾），选择下一个小时
        if (defaultMinuteIndex == 0
            && Integer.parseInt(defaultMinuteList.get(0)) < nextMinute
            && currentHour < 23) {
          defaultHourIndex = 1; // 选择下一个小时
          if (hours.get(0).size() > 1) { // 确保有下一个小时可选
            defaultMinuteList = minutes.get(0).get(1); // 获取下一个小时的分钟列表
            defaultMinuteIndex = 0; // 选择下一个小时的第一个分钟
          }
        }
      }
    } else {
      // 如果没有可用的分钟列表，创建一个默认的
      for (int m = 0; m <= 50; m += 10) {
        defaultMinuteList.add(String.format("%02d", m));
      }
    }

    try {
      // 尝试设置数据源
      pvTime.setNPicker(dates, hours.get(0), defaultMinuteList);
    } catch (Exception e) {
      e.printStackTrace();
      // 如果设置失败，尝试使用简化的数据结构
      List<List<String>> simpleMinutes = new ArrayList<>();
      simpleMinutes.add(defaultMinuteList);
      try {
        pvTime.setNPicker(dates, hours.get(0), simpleMinutes);
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
    pvTime.setSelectOptions(0, defaultHourIndex, defaultMinuteIndex);
  }

private void initListener() {
    // 设置下拉刷新监听
    fragmentGrabBinding.swipeRefreshLayout.setOnRefreshListener(this::applyFilters);

    // 设置RecyclerView滚动监听，实现上拉加载更多
    fragmentGrabBinding.recyclerView.addOnScrollListener(
        new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager =
                    (LinearLayoutManager) recyclerView.getLayoutManager();
                if (layoutManager != null) {
                    int visibleItemCount = layoutManager.getChildCount();
                    int totalItemCount = layoutManager.getItemCount();
                    int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();

                    // 判断是否滑动到底部，并且不是正在加载，并且不是最后一页
                    if (!isLoading
                        && !grabViewModel.isLastPage()
                        && (visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                        && firstVisibleItemPosition >= 0) {
                        isLoading = true;
                        String orderType = getSelectedOrderType();
                        String serviceType = getSelectedServiceType();
                        grabViewModel.loadNextPage(orderType, serviceType, selectedAppointmentTime);
                    }
                }
            }
        });

    // 设置订单项点击监听
    adapter.setOnItemClickListener((order, position) -> {
        // 处理订单项点击事件，可以跳转到订单详情页面
        OrderUnitVo orderUnitVo = new OrderUnitVo();
        orderUnitVo.setId(order.getOrderNo());
        orderUnitVo.setStartPosition(order.getStartPosition());
        orderUnitVo.setEndPosition(order.getEndPosition());
        orderUnitVo.setBookTime(order.getBookTime());
        orderUnitVo.setBookCarGrade(order.getCarType());
        orderUnitVo.setStatus(OrderStatusEnum.WAIT_FOR_ASSIGN.getValue());
        orderUnitVo.setOrderType(order.getOrderType());
        orderUnitVo.setSource(order.getSource());
        orderUnitVo.setIncome(order.getIncome());
        orderUnitVo.setFlightNo(order.getFlightNo());
        orderUnitVo.setFlightDate(order.getFlightDate());
        OrderDetailActivity.start(getActivity(), orderUnitVo);
    });

    // 设置抢单按钮点击监听
    adapter.setOnGrabClickListener((order, position) -> {
        // 处理抢单按钮点击事件，调用抢单接口
        Toast.makeText(getContext(), "抢单：" + order.getOrderNo(), Toast.LENGTH_SHORT).show();
    });

    // 预约时间选择
    fragmentGrabBinding.tvAppointmentTime.setOnClickListener(v -> {
        if (pvTime != null) {
            pvTime.show();
        }
    });

    // 订单类型选择变化监听
    fragmentGrabBinding.rgOrderType.setOnCheckedChangeListener((group, checkedId) -> applyFilters());

    // 车型选择变化监听
    if (rgServiceType != null) {
        rgServiceType.setOnCheckedChangeListener((group, checkedId) -> applyFilters());
    }
}

  private void applyFilters() {
    String orderType = getSelectedOrderType();
    String serviceType = getSelectedServiceType();
    // Ensure selectedAppointmentTime is in "yyyy-MM-dd HH:mm"
    grabViewModel.loadFirstPage(orderType, serviceType, selectedAppointmentTime);
  }

  private String getSelectedOrderType() {
    int selectedId = fragmentGrabBinding.rgOrderType.getCheckedRadioButtonId();
    if (selectedId == fragmentGrabBinding.rbPickUp.getId()) {
      return OrderTypeEnum.PICK_UP.getValue();
    } else if (selectedId == fragmentGrabBinding.rbDropOff.getId()) {
      return OrderTypeEnum.DROP_OFF.getValue();
    }
    return null; // "全部" or no selection
  }

  private String getSelectedServiceType() {
    if (rgServiceType == null) {
      return null; // "全部"
    }

    int selectedId = rgServiceType.getCheckedRadioButtonId();
    if (selectedId == -1 || selectedId == fragmentGrabBinding.rbAllServiceType.getId()) {
      return null; // "全部" 或没有选中任何选项
    }

    if (selectedId == fragmentGrabBinding.rbEconomics.getId()) {
      return ServiceType.ECONOMICS.getValue();
    } else if (selectedId == fragmentGrabBinding.rbComfort.getId()) {
      return ServiceType.COMFORT.getValue();
    } else if (selectedId == fragmentGrabBinding.rbLuxur.getId()) {
      return ServiceType.LUXUR.getValue();
    } else if (selectedId == fragmentGrabBinding.rbBusiness.getId()) {
      return ServiceType.BUSINESS.getValue();
    }
    
    return null; // "全部"
  }

  private void observeViewModel() {
    // 观察订单列表数据
    grabViewModel.getOrderListLiveData().observe(getViewLifecycleOwner(), this::handleOrderList);

    // 观察加载状态
    grabViewModel
        .getLoadingLiveData()
        .observe(
            getViewLifecycleOwner(),
            isLoading -> {
              fragmentGrabBinding.swipeRefreshLayout.setRefreshing(isLoading);
              this.isLoading = isLoading;
            });

    // 观察错误信息
    grabViewModel
        .getErrorLiveData()
        .observe(
            getViewLifecycleOwner(),
            errorMsg -> {
              if (getActivity() != null && !getActivity().isFinishing() && isResumed()) {
                ZMToast.err(getContext(), errorMsg);
              }
            });

    // 观察是否没有更多数据
    grabViewModel
        .getNoMoreDataLiveData()
        .observe(
            getViewLifecycleOwner(),
            noMoreData -> {
              if (noMoreData) {
                if (getActivity() != null && !getActivity().isFinishing() && isResumed()) {
                  ZMToast.info(getContext(), "我也是有底线的");
                }
              }
            });

    // 观察是否为空数据
    grabViewModel
        .getEmptyDataLiveData()
        .observe(
            getViewLifecycleOwner(),
            isEmpty -> {
              if (isEmpty) {
                fragmentGrabBinding.recyclerView.setVisibility(View.GONE);
                fragmentGrabBinding.emptyView.getRoot().setVisibility(View.VISIBLE);
              } else {
                fragmentGrabBinding.recyclerView.setVisibility(View.VISIBLE);
                fragmentGrabBinding.emptyView.getRoot().setVisibility(View.GONE);
              }
            });
  }

  private void handleOrderList(List<WaitOrderUnit> orderList) {
    if (grabViewModel.isCurrentPageGreaterThanFirst()
        && adapter.getItemCount() > 0
        && orderList != null
        && !orderList.isEmpty()) {
      // 加载更多数据
      adapter.addData(orderList);
    } else {
      // 刷新数据
      adapter.setData(orderList);
    }
  }

  @Override
  public void onDestroyView() {
    super.onDestroyView();
    if (pvTime != null && pvTime.isShowing()) {
      pvTime.dismiss();
    }
    fragmentGrabBinding = null;
  }
}
